import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux';
import {Block, View, Button, Image, Input, Text} from '@tarojs/components';
import {GetRequest, vcmonitor} from "../utils/tools";
import {newHttp} from "../utils/request";
import {http} from '../utils/http';
import {
    INDEX_DIY,
    GET_SITE_MODE,
    CREATE_ORDER_PAYEE_CODE,
    PAYEE_CODE_PAY,
    PAYEE_CODE_PAY_RESULT
} from "../constants/api";
import {
    CityLocation as CityLocationType,
    IndexDiyType
} from '../../utils/server.interface';
import {user} from '../utils/user.service';
import {h5Wx} from "../utils/h5.service";
import {payment} from "../utils/payment.service";
import {location as localtionServer} from '../utils/location.service';
import {PAY_URL} from "./enum";
import './inPay.scss';
// import VConsole from 'vconsole'

type PageStateProps = {
    location: CityLocationType
}

@connect(({location}) => ({
    location
}))

export default class InPay extends Component {
    state: {
        isSite: any,
        userData: object,
        avatar: string,
        payMoney: string,
        keyId: string,
        moneyId: string,
        orderData: object,
        canDirectPay: boolean,
        canSubmit: boolean,
    } = {
        isSite: 0,
        userData: null,
        avatar: "",
        payMoney: "",
        keyId: "",
        moneyId: "",
        orderData: null,
        canDirectPay: true,
        canSubmit: false
    }

    async UNSAFE_componentWillMount() {
        if (process.env.TARO_ENV === 'h5') {
            await h5Wx.getConfig()
        }
        const mode = await http.HGet(GET_SITE_MODE);

        const ua: any = window.navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i) != 'micromessenger') {
            Taro.showModal({
                title: '提示',
                content: '不是微信浏览器',
                showCancel: false,
                success: function (res) {}
            })
            return;
        }
        // localtionServer.autoLocation();

        const { price = 0, key, moneyId } = Taro.getCurrentInstance().router.params;
        // console.log("key : ", key);
        // console.log("moneyId : ", moneyId);

        // new VConsole()
        await user.checkLogin();
        const userData = await user.getUserData();
        // console.log("user data : ", userData);

        this.setState({
            isSite: mode.siteMode,
            userData: userData,
            avatar: userData.headimg,
            payMoney: price * 1 === 0 ? "" : price,
            keyId: key,
            moneyId: moneyId,
            canDirectPay: price * 1 > 0 ? true : false // 二维码有价格
        }, () => {
            if(this.state.canDirectPay) {
                const params = {
                    userId: userData.uuid,
                    money: this.state.payMoney,
                    "p-key": this.state.keyId,
                    "money_qr_code_id": this.state.moneyId
                };
                this.createOrder(params);
            }
        });
    }

    async componentDidShow() {
        vcmonitor(this)
    }

    // 创建订单
    createOrder = async (params) => {
        const orderResult = await newHttp.post(CREATE_ORDER_PAYEE_CODE, params, true);
        this.setState({ orderData: {...orderResult.data} });
    }

    // money change
    handleChangeMoney = e => {
        const { value } = e.detail;
        this.setState({ payMoney: value });
    }
    // 支付
    handlePay = async () => {
        // const reg = /^[1-9]\d*|\.\d*0|\.\d*[1-9]\d*$/;
        const reg = /(^[1-9]([0-9]+)?(.[0-9]{1,2})?$)|(^[0-9].[0-9]([0-9])?$)/;
        const {
            canDirectPay,
            payMoney,
            keyId,
            moneyId,
            userData: { uuid }
        } = this.state;

        if(!canDirectPay && !payMoney) {
            Taro.showToast({
                title: "请输入金额",
                icon: "none"
            });
            return;
        }else if(payMoney == 0) {
            Taro.showToast({
                title: "请输入有效金额",
                icon: "none"
            });
            return;
        }
        if(!reg.test(payMoney)) {
            Taro.showToast({
                title: "小数点后最多2位",
                icon: "none"
            });
            return;
        }

        if(!canDirectPay) {
            const params = {
                userId: uuid,
                money: payMoney,
                "p-key": keyId,
                "money_qr_code_id": moneyId
            };
            await this.createOrder(params);
        }

        const orderNum = this.state.orderData.order_num;
        Taro.showLoading({ title: "支付中, 请稍等..." });

        const payParams = { userId: uuid, rec_amount: payMoney };
        const result = await newHttp.post(PAYEE_CODE_PAY + orderNum, payParams);

        if(result) {
            Taro.setStorageSync('h5CodePay', "h5CodePay"); // 用于处理支付操作

            payment.payment(result.data, false, (status, res) => {
                if (process.env.TARO_ENV === 'h5') {
                    Taro.removeStorageSync('h5CodePay');
                    this.handlePayOperResult(status, res);
                }
            })
            /*payment.payment(result, false, res => {
                if (process.env.TARO_ENV === 'h5') {
                    document.addEventListener('WeixinJSBridgeReady', function () {
                        WeixinJSBridge.call('closeWindow');
                    }, false);
                    WeixinJSBridge.call('closeWindow');
                }
            })*/
        }else {
            Taro.hideLoading();
        }
    };
    // 支付操作结果
    handlePayOperResult = async (status, result) => {
        const {
            orderData: { order_num: orderNum },
            userData: { uuid }
        } = this.state;
        const payResultParams = { userId: uuid, isPay: status };
        const res = await newHttp.post(PAYEE_CODE_PAY_RESULT + orderNum, payResultParams);
        if(res) console.log("支付操作结果 : ", res);
    }

    render() {
        const { avatar, payMoney, canDirectPay, canSubmit } = this.state;

        return (
            <View className='pay-root'>
                <View className='avatar-view'>
                    <Image src={avatar} className='avatar-img' />
                </View>

                <View className="price-box">
                    <View className="price-text">金额（元）</View>
                    <View className="price-enter">
                        <Text className="price-kind">￥</Text>
                        {
                            !canDirectPay ?
                            <Input
                                className="weui-input"
                                type="number"
                                value={payMoney}
                                placeholder="请输入金额"
                                placeholderStyle="font-size: 18px"
                                onInput={this.handleChangeMoney}
                            />
                            :
                            <Text>{ payMoney }</Text>
                        }
                    </View>
                </View>

                <View className="pay-btn">
                    <Button type="primary" onClick={this.handlePay}>去支付</Button>
                    <Text className="tip-text">支付完成后，如需退款请及时联系卖家</Text>
                </View>
            </View>
        )
    }
}
